using System;
using System.Linq;
using System.Reflection;
using Mbs.ComponentModel.Container.Metadata;

namespace Mbs.ComponentModel.Container.Loader
{
    [Serializable]
    public class AssemblyLoader : LoaderAdapter
    {
        private readonly Assembly Assembly;
        public AssemblyLoader(Assembly assembly)
        {
            Assembly = assembly;
        }

        public override void Load()
        {
            if (Assembly != null && Kernel != null)
            {
                var items = (from t in Assembly.GetTypes()
                             let attrs = t.GetCustomAttributes(typeof(ComponentAttribute), true).Cast<ComponentAttribute>().ToArray()
                             where attrs != null && attrs.Length == 1
                             select new { Implemention = t, Option = attrs[0] }).ToArray();

                if (items != null && items.Length > 0)
                {
                    string id = null;
                    foreach (var item in items)
                    {
                        id = string.IsNullOrEmpty(item.Option.Id) ? item.Implemention.FullName : item.Option.Id;
                        Kernel.Register(new ComponentInfo(id, item.Option.Service, item.Implemention, item.Option.Activator, item.Option.LifestyleType, item.Option.IsLazyInit));
                    }
                }
            }
        }
    }
}
